package com.swensen.game.data;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.swensen.game.data.Tile.TileId;
import com.swensen.game.data.Tile.TileType;
import com.swensen.game.data.TileLoader.TileLoadingData;


/**
 * The Enum TileSet.
 */
public class TileSet {
	
	/** The tiles. */
	private List<Tile> tiles;
	//private String name;
	
	private Map<String, List<BufferedImage>> tileData;
	
	/**
	 * Gets the files in path.
	 *
	 * @param path the path
	 * @return the files in path
	 * @throws URISyntaxException the uRI syntax exception
	 */
	private File[] getFilesInPath(String path) throws URISyntaxException {
		String current = "";
		try {
			current = new File(".").getCanonicalPath();
			System.out.println(current);
			path = "." + File.separator + path;
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		File file = new File(path);
		return file.listFiles();
	}
	
	public BufferedImage getImage(TileId data) {
		List<BufferedImage> images = tileData.get(data.getFileName());
		if (images == null) {
			return null;
		}
		return images.size() > data.getTileNumber() ? images.get(data.getTileNumber()) : null;
	}
	
	/**
	 * Gets the tiles.
	 *
	 * @return the tiles
	 */
	public List<Tile> getTiles() {
		return tiles;
	}
	
	/**
	 * Load set.
	 *
	 * @param path the path
	 */
	public void loadSet(String path) {
		tileData = new HashMap<String, List<BufferedImage>>();
		tiles = new ArrayList<Tile>();
		File[] dir;
		try {
			dir = getFilesInPath(path);
		} catch(URISyntaxException e) {
			return;
		}
		
		if (dir == null) {
			return;
		}
		
		List<TileLoadingData> loadingData = new ArrayList<TileLoadingData>();
		
		for (File file : dir) {
			String fileName = file.getName();
			int index = fileName.lastIndexOf('.');
			if (index == -1) {
				continue;
			}
			
			String extension = fileName.substring(index + 1);
			if (extension.equals(TileType.BASIC.getExtension())) {
				loadingData.add(new TileLoadingData(file, TileType.BASIC));
			}
			else if (extension.equals(TileType.ANIMATED.getExtension())) {
				loadingData.add(new TileLoadingData(file, TileType.ANIMATED));
			}
		}
		
		if (loadingData.size() > 0) {
			tiles = TileLoader.loadTiles(loadingData, tileData);
		}
	}
}
